package com.code.statistics.services.impl;

import com.code.statistics.daos.InOutGroupMapper;
import com.code.statistics.managers.HttpManager;
import com.code.statistics.models.Dict;
import com.code.statistics.models.InOutGroup;
import com.code.statistics.models.StatisticsGroup;
import com.code.statistics.services.DictService;
import com.code.statistics.services.InOutGroupService;
import com.code.statistics.services.StatisticsGroupService;
import com.code.statistics.utils.TimeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 当日入群与退群的统计业务实现类
 *
 * @author xiaoyaowang
 */
@Service
public class InOutGroupServiceImpl implements InOutGroupService {

    @Resource
    private StatisticsGroupService statisticsGroupService;

    @Resource
    private DictService dictService;

    @Resource
    private InOutGroupService inOutGroupService;

    @Resource
    private InOutGroupMapper inOutGroupMapper;

    @Resource
    private HttpManager httpManager;

    @Override
    public void synInOutGroupInCurrentDay() {
        // 获取所有组
        List<StatisticsGroup> statisticsGroupList = statisticsGroupService.getStatisticsGroupList();
        if (CollectionUtils.isEmpty(statisticsGroupList)) {
            return;
        }
        String groupUrl;
        String initialMembersStr;
        int initialMembers;
        Integer totalMembers;
        int members;
        InOutGroup inOutGroup;
        List<InOutGroup> inOutGroupList = new ArrayList<>();
        Dict dict;
        int size = statisticsGroupList.size();
        List<Dict> dictList = new ArrayList<>(size);
        for (StatisticsGroup statisticsGroup : statisticsGroupList) {
            groupUrl = statisticsGroup.getGroupUrl();
            initialMembers = 0;
            members = 0;
            initialMembersStr = dictService.getDictValueByDictKey(groupUrl);
            if (StringUtils.isNotBlank(initialMembersStr)) {
                initialMembers = Integer.parseInt(initialMembersStr);
            }
            totalMembers = httpManager.getNewChatMemberCount(statisticsGroup.getGroupChatId());
            if (totalMembers == initialMembers) {
                continue;
            }
            inOutGroup = new InOutGroup();
            inOutGroup.setGroupUrl(groupUrl);
            // 新人入群
            if (totalMembers > initialMembers) {
                members = totalMembers - initialMembers;
                inOutGroup.setInOutType(1);
            }
            // 退群人数
            if (totalMembers < initialMembers) {
                members = initialMembers - totalMembers;
                inOutGroup.setInOutType(2);
            }

            inOutGroup.setMembers(members);
            inOutGroupList.add(inOutGroup);

            dict = new Dict();
            dict.setDictKey(groupUrl);
            if (dictService.whetherExistDictKey(groupUrl)) {
                dict.setRemark("1");
            } else {
                dict.setCreatedAt(new Date());
                dict.setDeleted(0);
                dict.setRemark("0");
            }
            dict.setUpdatedAt(new Date());
            dict.setDictValue(String.valueOf(totalMembers));
            dictList.add(dict);
        }
        inOutGroupService.insertInOutGroupListAndPatchUpdateDictList(dictList, inOutGroupList);
    }

    @Transactional(transactionManager = "testTransactionManager", rollbackFor = Exception.class)
    @Override
    public int insertInOutGroupListAndPatchUpdateDictList(List<Dict> dictList, List<InOutGroup> inOutGroupList) {
        int count = 0;
        if (!CollectionUtils.isEmpty(inOutGroupList)) {
            String currentDayStr = TimeUtil.nowDateWithYmd();
            Date currentDay = new Date();
            inOutGroupList.forEach(item -> {
                item.setCurrentDay(currentDayStr);
                item.setCreatedAt(currentDay);
                item.setUpdatedAt(currentDay);
                item.setDeleted(0);
            });
            count += inOutGroupMapper.insertList(inOutGroupList);
        }
        if (!CollectionUtils.isEmpty(dictList)) {
            count += dictService.patchUpdateDictByDictKeys(dictList);
        }
        return count;
    }

    @Override
    public int deleteInOutGroupByCurrentDay(String currentDay) {
        return inOutGroupMapper.deleteInOutGroupByCurrentDay(currentDay);
    }

    @Override
    public List<Integer> getMembersByGroupUrlAndInOutTypeInCurrentDay(String groupUrl, Integer inOutType, String currentDay) {
        return inOutGroupMapper.getMembersByGroupUrlAndInOutTypeInCurrentDay(groupUrl, inOutType, currentDay);
    }
}
